package com.serviets;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @Author:路老师
 * @Description:基本Servlet类，具体业务的Servlet都要继承该Servlet
 */
public class BaseServiets extends HttpServlet {
    protected PrintWriter out;//声明输出流对象
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
//设置request对象的编码集
            request.setCharacterEncoding("UTF-8");
//设置响应的结果类型及编码
            response.setContentType("application/json;charset=utf-8");
//获得输出流对象
            out = response.getWriter();
//获得客户端传入的operate参数，该参数为方法的方法名
            String methodName = request.getParameter("operate");
//根据方法名和参数列表获得方法对象
            Method method = this.getClass().getDeclaredMethod(methodName,HttpServletRequest.class,HttpServletResponse.class);

//调用方法
            method.invoke(this,request,response);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
